const prisma = require('../utils/prisma');
const { success, error } = require('../utils/response');

/**
 * 获取通知列表
 * @route GET /api/notifications
 */
const getNotifications = async (req, res) => {
  try {
    const notifications = await prisma.notification.findMany({
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    });
    
    return success(res, notifications);
  } catch (err) {
    console.error('Get notifications error:', err);
    return error(res, 'Failed to get notifications', 500);
  }
};

/**
 * 获取指定通知
 * @route GET /api/notifications/:id
 */
const getNotificationById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const notification = await prisma.notification.findUnique({
      where: { id },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    if (!notification) {
      return error(res, 'Notification not found', 404);
    }
    
    return success(res, notification);
  } catch (err) {
    console.error('Get notification error:', err);
    return error(res, 'Failed to get notification', 500);
  }
};

/**
 * 创建通知
 * @route POST /api/notifications
 */
const createNotification = async (req, res) => {
  try {
    const { content } = req.body;
    const userId = req.user.id;
    
    if (!content) {
      return error(res, 'Content is required', 400);
    }
    
    // 创建通知
    const notification = await prisma.notification.create({
      data: {
        content,
        userId,
        read: false
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    return success(res, notification, 'Notification created successfully', 201);
  } catch (err) {
    console.error('Create notification error:', err);
    return error(res, 'Failed to create notification', 500);
  }
};

/**
 * 更新通知
 * @route PUT /api/notifications/:id
 */
const updateNotification = async (req, res) => {
  try {
    const { id } = req.params;
    const { content, read } = req.body;
    
    // 检查通知是否存在
    const existingNotification = await prisma.notification.findUnique({
      where: { id }
    });
    
    if (!existingNotification) {
      return error(res, 'Notification not found', 404);
    }
    
    // 检查权限（只有管理员或通知创建者可以更新内容）
    if (content && req.user.role !== 'admin' && req.user.id !== existingNotification.userId) {
      return error(res, 'Permission denied', 403);
    }
    
    // 准备更新数据
    const updateData = {};
    
    if (content) updateData.content = content;
    if (read !== undefined) updateData.read = read;
    
    // 更新通知
    const updatedNotification = await prisma.notification.update({
      where: { id },
      data: updateData,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    return success(res, updatedNotification, 'Notification updated successfully');
  } catch (err) {
    console.error('Update notification error:', err);
    return error(res, 'Failed to update notification', 500);
  }
};

/**
 * 删除通知
 * @route DELETE /api/notifications/:id
 */
const deleteNotification = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查通知是否存在
    const existingNotification = await prisma.notification.findUnique({
      where: { id }
    });
    
    if (!existingNotification) {
      return error(res, 'Notification not found', 404);
    }
    
    // 检查权限（只有管理员或通知创建者可以删除）
    if (req.user.role !== 'admin' && req.user.id !== existingNotification.userId) {
      return error(res, 'Permission denied', 403);
    }
    
    // 删除通知
    await prisma.notification.delete({
      where: { id }
    });
    
    return success(res, null, 'Notification deleted successfully');
  } catch (err) {
    console.error('Delete notification error:', err);
    return error(res, 'Failed to delete notification', 500);
  }
};

module.exports = {
  getNotifications,
  getNotificationById,
  createNotification,
  updateNotification,
  deleteNotification
};
